<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <br/>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 警告区域区域 -->
      <el-alert title="注意: 只允许为第三级参数设置相关参数" type="warning" :closable="false" show-icon></el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类: &nbsp;&nbsp;&nbsp;</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader v-model="selectedCategoryKeys" :options="categoryList"
                       :props="cascaderProps" @change="handleChange" clearable>
          </el-cascader>
        </el-col>
      </el-row>

      <!-- tab页签区域 -->
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加动态参数的按钮 -->
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加参数</el-button>

          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand"> <!-- 展开行 -->
              <template slot-scope="scope">
                <!-- 循环渲染Tag标签 -->
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index, scope.row)">{{item}}</el-tag>

                <!-- 输入的文本框 -->
                <el-input v-if="scope.row.inputVisible" class="input-new-tag" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                <!-- 添加的按钮 -->
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#" width="60"></el-table-column> <!-- 索引列 -->
            <el-table-column prop="attr_name" label="参数名称" min-width="180"></el-table-column>
            <el-table-column label="操作" min-width="180">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button> <!-- 编辑按钮 -->
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button> <!-- 删除按钮 -->
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加静态属性的按钮 -->
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加属性</el-button>

          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand"> <!-- 展开行 -->
              <template slot-scope="scope">
                <!-- 循环渲染Tag标签 -->
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index, scope.row)">{{item}}</el-tag>

                <!-- 输入的文本框 -->
                <el-input v-if="scope.row.inputVisible" class="input-new-tag" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                <!-- 添加的按钮 -->
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#" width="60"></el-table-column> <!-- 索引列 -->
            <el-table-column prop="attr_name" label="属性名称" min-width="180"></el-table-column>
            <el-table-column label="操作" min-width="180">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button> <!-- 编辑按钮 -->
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button> <!-- 删除按钮 -->
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数或属性的对话框 -->
    <el-dialog :title="'添加'+titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- 内容主体区 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name" placeholder="请输入名称"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改参数或属性的对话框 -->
    <el-dialog :title="'修改'+titleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 内容主体区 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name" placeholder="请输入名称"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      categoryList: [], // 商品分类数据列表
      cascaderProps: { // 指定级联选择器配置对象
        expandTrigger: 'hover', // 次级菜单的展开方式
        value: 'cat_id', // 指定选项的值为选项对象的某个属性值
        label: 'cat_name', // 指定选项标签为选项对象的某个属性值
        children: 'children' // 指定选项的子选项为选项对象的某个属性值
      },
      selectedCategoryKeys: [], // 级联选择框双向绑定的数组

      activeName: 'many', // 被激活的页签的名称
      manyTableData: [], // 动态参数列表数据
      onlyTableData: [], // 静态属性列表数据

      addDialogVisible: false, // 控制添加对话框的显示与隐藏
      addForm: {}, // 添加参数的表单数据对象
      addFormRules: { // 添加表单的验证验证规则对象
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ]
      },

      editDialogVisible: false, // 控制修改对话框的显示与隐藏
      editForm: {}, // 修改参数的表单数据对象
      editFormRules: { // 修改表单的验证验证规则对象
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCategoryList()
  },
  methods: {
    // 获取所有的商品分类列表
    async getCategoryList() {
      const { data: res } = await this.$http.get('categories', { type: 3 })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(' 获取商品分类数据列表失败')
      }
      this.categoryList = res.data // 把数据列表赋值给categoryList
    },

    // 级联选择框选中项变化时会触发这个函数
    handleChange() {
      this.getAttributesData()
      // console.log(this.selectedCategoryKeys)
    },

    // Tab页签点击事件的处理
    handleClick() {
      // console.log(this.activeName)
      this.getAttributesData()
    },

    // 根据所选分类的Id, 和当前所处的面板, 获取对应的参数列表
    async getAttributesData() {
      if (this.selectedCategoryKeys.length !== 3) { // 选中的不是三级分类
        this.$message.error('选中的不是三级分类')
        this.selectedCategoryKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      const { data: res } = await this.$http.get(`categories/${this.categoryId}/attributes`, {
        params: { sel: this.activeName }
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(' 获取参数列表失败')
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputVisible = false // 控制按钮与文本框的切换显示
        item.inputValue = '' // 文本框中输入的内容
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },

    // 监听添加对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定按钮,添加参数
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.categoryId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        // console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.$message.success('添加参数成功')
        this.addDialogVisible = false
        this.getAttributesData()
      })
    },

    // 点击编辑按钮,显示修改对话框
    async showEditDialog(attrId) {
      const { data: res } = await this.$http.get(`categories/${this.categoryId}/attributes/${attrId}`, {
        params: {
          attr_sel: this.activeName
        }
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(' 获取参数信息失败')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听修改对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 点击确定按钮,修改参数
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.categoryId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数失败')
        }
        this.$message.success('修改参数成功')
        this.getAttributesData()
        this.editDialogVisible = false
      })
    },

    // 点击删除按钮, 删除参数
    async removeParams(attrId) {
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果确认删除,则返回值为字符串confirm ; 如果取消删除,则返回值为字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete(`categories/${this.categoryId}/attributes/${attrId}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败')
      }
      this.$message.success('删除参数成功')
      this.getAttributesData()
    },

    // 点击按钮,显示文本输入框
    showInput(row) {
      row.inputVisible = true
      // 让文本框自动获得焦点
      // $nextTick方法的作用,就是当页面上元素被重新渲染之后,才会执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 文本框失去了焦点, 或按下了Enter键都会触发
    handleInputConfirm(row) {
      // 如果输入的内容有效(不为空),则需要对内容做后续处理
      if (row.inputValue.trim().length !== 0) { // trim()去掉字符串左右两边的空格
        row.attr_vals.push(row.inputValue.trim())
        this.saveAttrVals(row) // 需要发起网络请求,将新增参数保存到后台数据库中
      }
      row.inputValue = ''
      row.inputVisible = false
    },
    // 删除对应的参数可选项
    handleClose(index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row) // 需要发起网络请求,将删除后的参数保存到后台数据库中
    },
    // 将对attr_vals的操作,保存到数据库中
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(`categories/${this.categoryId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败')
      }
      this.$message.success('修改参数项成功')
    }
  },
  computed: {
    // 如果按钮需要被禁用,则返回true, 否则返回false
    isBtnDisabled() {
      return this.selectedCategoryKeys.length !== 3
    },

    // 当前选中的三级分类的Id
    categoryId() {
      if (this.selectedCategoryKeys.length === 3) {
        return this.selectedCategoryKeys[2]
      }
      return null
    },

    // 动态计算标题的文本
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .cat_opt {
    margin: 15px 0;
  }
  .el-cascader {
    width: 300px;
  }
  .el-tag {
    margin: 5px;
  }
  .input-new-tag {
    width: 120px;
  }
</style>
